package com.wanggsx.library.base.views;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.core.content.res.ResourcesCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.wanggsx.library.util.UtilsSize;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FlowLayoutSingleMode extends ViewGroup {

    public FlowLayoutSingleMode(Context context) {
        super(context);
    }

    public FlowLayoutSingleMode(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayoutSingleMode(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    int textViewDrawableId,  selectTextColor, normalTextColor, notEnableTextColor, notEnableTextViewDrawableId;

    //选项数据源
    private List<TextView> mListTextViews = new ArrayList<>();
    //当前选项索引
    private int mSelectIndex = -1;
    //不可选数据源
    private List<TextView> mListNotEnabledTextViews = new ArrayList<>();


    /**
     * 初始化数据源
     * */
    public void initDatas(Context context, List<String>  datas, List<String> notEnabledDatas, int selectIndex, int textViewDrawableId, int selectTextColor,int normalTextColor,int notEnableTextColor,int notEnableTextViewDrawableId){
        this.textViewDrawableId = textViewDrawableId;
        this.selectTextColor = selectTextColor;
        this.normalTextColor= normalTextColor;
        this.notEnableTextColor = notEnableTextColor;
        this.notEnableTextViewDrawableId = notEnableTextViewDrawableId;
        //清理
        removeAllViews();
        //添加待选项
        if (datas!=null&&datas.size()>=1){
            for (int i=0;i < datas.size();i++){
                addData(context,datas.get(i),textViewDrawableId,normalTextColor,selectTextColor);
                //设置要选择的项
                if (selectIndex>=0 && selectIndex < datas.size() && i == selectIndex){
                    setSelectedIndex(selectIndex);
                }
            }
        }
        //添加不可选项
        if (notEnabledDatas!=null&&notEnabledDatas.size()>=1){
            for (int i=0;i < notEnabledDatas.size();i++){
                TextView textView = new TextView(context);
                textView.setTextSize(12);
                textView.setText(datas.get(i));
                int dp3px = UtilsSize.dp2px(3);
                //设置外边距
                MarginLayoutParams params = new MarginLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                params.setMargins(dp3px,dp3px*2,dp3px,0);
                textView.setLayoutParams(params);
                //设置内边距
                textView.setPadding(dp3px*2,dp3px,dp3px*2,dp3px);
                //设置字体颜色
                if (notEnableTextColor>0){
                    textView.setTextColor(getResources().getColor(notEnableTextColor));
                }
                //添加删除线
                textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                //添加背景
                if (notEnableTextViewDrawableId>=1){
                    textView.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),notEnableTextViewDrawableId,null));
                }
                addView(textView);
                mListTextViews.add(textView);
            }
        }
    }

    /**
     * 添加数据源
     * */
    public void addData(Context context, String data , int textViewDrawableId, final int normalTextColor, final int selectTextColor){
        TextView textView = new TextView(context);
        textView.setText(data);
        textView.setTextSize(12);
        int dp3px = UtilsSize.dp2px(3);
        //设置外边距
        MarginLayoutParams params = new MarginLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        params.setMargins(dp3px*3,dp3px*2,0,0);
        textView.setLayoutParams(params);
        //设置内边距
        textView.setPadding(dp3px*2,dp3px,dp3px*2,dp3px);
        //设置字体颜色
        if (normalTextColor>0){
            textView.setTextColor(getResources().getColor(normalTextColor));
        }
        //设置字体控件背景
        if (textViewDrawableId>=1){
            textView.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),textViewDrawableId,null));
            textView.setEnabled(true);
        }
        //添加字体控件
        addView(textView);
        mListTextViews.add(textView);
        final int index = mListTextViews.size()-1;
        //添加点击事件
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setSelectedIndex(index);
            }
        });
    }
    /**
     * 删除某条数据
     * */
    public void removeIndex(String data){
        for (int i = 0;i<mListTextViews.size();i++){
            TextView tv = mListTextViews.get(i);
            if (mSelectIndex == i){
                tv.setSelected(false);
                mSelectIndex = -1;
            }
            if (tv!=null && tv.getText().toString().equals(data)){
                removeView(tv);
                mListTextViews.remove(tv);
                return;
            }
        }
    }

    /**
     * 清理数据
     * */
    public void clearDatas(){
        mSelectIndex = -1;
        for (TextView tv : mListTextViews){
            if (tv!=null){
                removeView(tv);
            }
        }
        mListTextViews.clear();
        for (TextView tv : mListNotEnabledTextViews){
            if (tv!=null){
                removeView(tv);
            }
        }
        mListNotEnabledTextViews.clear();
    }

    public int getSelectIndex(){
        return this.mSelectIndex;
    }

    public String getSelectText(){
        if (this.mSelectIndex>=0 && this.mSelectIndex+1<=this.mListTextViews.size()){
            return this.mListTextViews.get(this.mSelectIndex).getText().toString();
        }
        return null;
    }

    /**
     * 选中指定索引的数据源
     * @param index
     */
    public void setSelectedIndex(int index){
        //取消选中
        if (mSelectIndex>=0 && mListTextViews!=null && mListTextViews.size()-1>=mSelectIndex){
            TextView tv = mListTextViews.get(mSelectIndex);
            tv.setEnabled(true);
            if (normalTextColor > 0){
                tv.setTextColor(getResources().getColor(normalTextColor));
            }
        }
        //选中
        if (index >= 0&& index < mListTextViews.size()){
            mSelectIndex = index;
            TextView tv = mListTextViews.get(mSelectIndex);
            tv.setEnabled(false);
            if (selectTextColor > 0){
                tv.setTextColor(getResources().getColor(selectTextColor));
            }
        }
        //回调监听对象
        if (mListener!=null){
            mListener.onChanged(mListTextViews.get(mSelectIndex).getText().toString(),mSelectIndex);
        }
    }

    /**
     * 根据文本返回指定索引
     * @param text
     * @return
     */
    private int getIndexFromText(String text){
        for (int i=0;i<mListTextViews.size();i++){
            if (mListTextViews.get(i).getText().toString().trim().equals(text)){
                return i;
            }
        }
        return -1;
    }

    /**
     * 选中指定内容的数据源
     * @param text
     */
    public boolean setSelectedText(String text){
        int index = getIndexFromText(text);
        if (index>=0){
            setSelectedIndex(index);
            return true;
        }
        return false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //   super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //遍历去调用所有子元素的measure方法（child.getMeasuredHeight()才能获取到值，否则为0）
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = 0, measuredHeight = 0;
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widtMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        //由于计算子view所占宽度，这里传值需要自身减去PaddingRight宽度，PaddingLeft会在接下来计算子元素位置时加上
        Map<String, Integer> compute = compute(widthSize-getPaddingRight());

        //EXACTLY模式：对应于给定大小或者match_parent情况
        if (widtMode == MeasureSpec.EXACTLY) {
            measuredWidth = widthSize;
            //AT_MOS模式：对应wrap-content（需要手动计算大小，否则相当于match_parent）
        } else if (widtMode == MeasureSpec.AT_MOST) {
            measuredWidth = compute.get("allChildWidth");
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            measuredHeight = heightSize;
        } else //if (heightMode == MeasureSpec.AT_MOST)
        {
            measuredHeight = compute.get("allChildHeight");
        }
        //设置flow的宽高
        setMeasuredDimension(measuredWidth,measuredHeight);
    }

    //监听对象
    private OnSelectChangedListener mListener;

    public void setmListener(OnSelectChangedListener mListener) {
        this.mListener = mListener;
    }

    public interface OnSelectChangedListener{
        void onChanged(String text, int index);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            Rect rect = (Rect) getChildAt(i).getTag();
            child.layout(rect.left,rect.top,rect.right,rect.bottom);
        }

    }

    /**
     * 测量过程
     * @param flowWidth 该view的宽度
     * @return  返回子元素总所占宽度和高度（用于计算Flowlayout的AT_MOST模式设置宽高）
     */
    private Map<String, Integer> compute(int flowWidth) {
        //是否是单行
        boolean aRow = true;
        MarginLayoutParams marginParams;//子元素margin
        int rowsWidth = getPaddingLeft();//当前行已占宽度(注意需要加上paddingLeft)
        int columnHeight =getPaddingTop();//当前行顶部已占高度(注意需要加上paddingTop)
        int rowsMaxHeight = 0;//当前行所有子元素的最大高度（用于换行累加高度）

        for (int i = 0; i <  getChildCount(); i++) {

            View child = getChildAt(i);
            //获取元素测量宽度和高度
            int measuredWidth = child.getMeasuredWidth();
            int measuredHeight = child.getMeasuredHeight();
            //获取元素的margin
            if (child.getLayoutParams() instanceof  MarginLayoutParams){
                marginParams = (MarginLayoutParams) child.getLayoutParams();
            }else{
                marginParams = (MarginLayoutParams) new MarginLayoutParams(child.getLayoutParams());
                child.setLayoutParams(marginParams);
            }

            //子元素所占宽度 = MarginLeft+ child.getMeasuredWidth+MarginRight  注意此时不能child.getWidth,因为界面没有绘制完成，此时wdith为0
            int childWidth = marginParams.leftMargin + marginParams.rightMargin + measuredWidth;
            int childHeight = marginParams.topMargin + marginParams.bottomMargin + measuredHeight;
            //判断是否换行： 该行已占大小+该元素大小>父容器宽度  则换行

            rowsMaxHeight = Math.max(rowsMaxHeight, childHeight);
            //换行
            if (rowsWidth + childWidth > flowWidth) {
                //重置行宽度
                rowsWidth = getPaddingLeft()+getPaddingRight();
                //累加上该行子元素最大高度
                columnHeight += rowsMaxHeight;
                //重置该行最大高度
                rowsMaxHeight = childHeight;
                aRow = false;
            }
            //累加上该行子元素宽度
            rowsWidth += childWidth;
            //判断时占的宽段时加上margin计算，设置顶点位置时不包括margin位置，不然margin会不起作用，这是给View设置tag,在onlayout给子元素设置位置再遍历取出
            child.setTag(new Rect(rowsWidth - childWidth + marginParams.leftMargin, columnHeight + marginParams.topMargin, rowsWidth - marginParams.rightMargin, columnHeight + childHeight - marginParams.bottomMargin));
        }

        //返回子元素总所占宽度和高度（用于计算Flowlayout的AT_MOST模式设置宽高）
        Map<String, Integer> flowMap = new HashMap<>();
        //单行
        if (aRow) {
            flowMap.put("allChildWidth", rowsWidth);
        } else {
            //多行
            flowMap.put("allChildWidth", flowWidth);
        }
        //FlowLayout测量高度 = 当前行顶部已占高度 +当前行内子元素最大高度+FlowLayout的PaddingBottom
        flowMap.put("allChildHeight", columnHeight+rowsMaxHeight+getPaddingBottom());
        return  flowMap;
    }
}